<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="父级栏目" prop="parentId">
        <el-cascader
          v-model="queryParams.parentId"
          :options="categoryTree"
          :props="{ checkStrictly: true, expandTrigger: 'hover', value: 'id', label: 'title', emitPath: false }"
          clearable></el-cascader>
      </el-form-item>
      <el-form-item label="栏目名称" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入栏目名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['Category:category:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['Category:category:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['Category:category:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="categoryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="栏目名称" align="center" prop="title" />
      <el-table-column label="父级栏目" align="center" prop="parentName" />
      <el-table-column label="排序" align="center" prop="sortOrder" />
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['Category:category:edit']"
            v-if="scope.row.canEdit === 1"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['Category:category:remove']"
            v-if="scope.row.canEdit === 1"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改Category对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body  :close-on-click-modal="false" modal :destroy-on-close="true">
      <el-form ref="form" :model="form" :rules="rules" label-width="160px" >
        <el-form-item label="是否是顶级栏目">
          <el-radio-group v-model="form.isIndexCategory" @change="isIndexCategoryChange">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="父级栏目" v-if="!form.isIndexCategory">
          <el-cascader
            v-model="form.parentId"
            :options="categoryTree"
            :props="{ checkStrictly: true, expandTrigger: 'hover', value: 'id', label: 'title', emitPath: false }"
            clearable></el-cascader>
        </el-form-item>
        <el-form-item label="栏目名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入栏目名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input v-model="form.sortOrder" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="栏目是否禁用">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="启用外链">
          <el-radio-group v-model="form.isWebUel">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="外链地址" prop="webUrl" v-if="form.isWebUel == 1">
          <el-input v-model="form.webUrl" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="封面图片">
          <image-upload :value="form.cover" @input="coverInput"></image-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCategory, getCategory, delCategory, addCategory, updateCategory, exportCategory, getCategoryTree } from "@/api/business/category";
import ImageUpload from '@/components/ImageUpload';

export default {
  name: "Category",
  components: {
    ImageUpload,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // Category表格数据
      categoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 栏目位置字典
      positionOptions: [],
      // 状态字典
      statusOptions: [],
      // 是否可在后台进行编辑字典
      canEditOptions: [],
      // 是否是外链字典
      isWebUelOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        isIndexCategory: null,
        parentId: null,
        title: null,
        position: 3,
        sortOrder: null,
        status: null,
        isWebUel: null,
      },
      // 表单参数
      form: {},
      // 栏目树
      categoryTree: [],
      rules: {
        title: [
          { required: true, message: '栏目标题不允许为空', trigger: 'blur' }
        ]
      },
    };
  },
  created() {
    this.getCategoryTree();
    this.getList();
    this.getDicts("business_position").then(response => {
      this.positionOptions = response.data;
    });
    this.getDicts("business_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("business_status").then(response => {
      this.canEditOptions = response.data;
    });
    this.getDicts("business_status").then(response => {
      this.isWebUelOptions = response.data;
    });
  },
  methods: {
    /** 上传图片回调 */
    coverInput(url) {
      this.form.cover = url
      this.$forceUpdate()
    },
    /** 切换父级id */
    isIndexCategoryChange(value) {
      if (value == 1) {
        this.form.parentId = 0
      }
    },
    /** 查询栏目树 */
    getCategoryTree() {
      getCategoryTree({position: 3}).then(response => {
        this.categoryTree = response.data
      })
    },
    /** 查询Category列表 */
    getList() {
      this.loading = true;
      listCategory(this.queryParams).then(response => {
        this.categoryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 栏目位置字典翻译
    positionFormat(row, column) {
      return this.selectDictLabel(this.positionOptions, row.position);
    },
    // 状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 是否可在后台进行编辑字典翻译
    canEditFormat(row, column) {
      return this.selectDictLabel(this.canEditOptions, row.canEdit);
    },
    // 是否是外链字典翻译
    isWebUelFormat(row, column) {
      return this.selectDictLabel(this.isWebUelOptions, row.isWebUel);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        isIndexCategory: 0,
        parentId: 0,
        title: null,
        position: 3,
        sortOrder: 0,
        status: 1,
        isWebUel: 0,
        webUrl: null,
        cover: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加Category";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCategory(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改Category";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if ( this.form.isIndexCategory === 0 && this.form.parentId.trim() == '' ) {
            this.msgError("不是顶级栏目则必须选择父级栏目");
            return
          }else if (this.form.isIndexCategory === 1) {
            this.form.parentId = 0
          }
          this.form.position = 3
          if (this.form.id != null) {
            updateCategory(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.getCategoryTree();
            });
          } else {
            addCategory(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.getCategoryTree();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除Category编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delCategory(ids);
      }).then(() => {
        this.getList();
        this.getCategoryTree();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有Category数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportCategory(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    }
  }
};
</script>
